﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
    string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["xxnewsConnectionString"].ConnectionString;
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["pn"] == "" || Session["pn"] == null)
        {
            Response.Redirect("default.aspx");
        }
        if (Session["pngeren"] == "" || Session["pngeren"] == null)
        {
            Response.Redirect("default.aspx");
        }
        if (!IsPostBack)
        {
            Label1.Text = Session["pnchejian"].ToString();
            Label2.Text = Session["pn"].ToString();
            Label3.Text = Session["pngeren"].ToString();
            if (Label1.Text == Label2.Text) Label1.Visible = false;
            this.txtChangeTime.Text = DateTime.Today.ToString("yyyy-MM-dd");
            //非设备科材料科不能删除记录。
            this.GridView1.Columns[0].Visible = !(Session["pn"].ToString().Contains("设备科") == false);
            g_bind();
        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#D1DDF1'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                //因为此处都是消费记录，因此只要有权限，都可以删除
                ((LinkButton)e.Row.Cells[0].Controls[0]).Attributes.Add("onclick", "javascript:return confirm('你确认要删除这条记录吗?')");
            }
            //卡的班组和加油班组不同。
            if (this.GridView1.DataKeys[e.Row.RowIndex]["bzname_"].ToString() != this.GridView1.DataKeys[e.Row.RowIndex]["bzname"].ToString())
            {
                ((DataControlFieldCell)e.Row.Cells[8]).ForeColor = System.Drawing.Color.Red;
            }
            //卡的车号和加油车号不同。
            if (this.GridView1.DataKeys[e.Row.RowIndex]["carnum_"].ToString() != this.GridView1.DataKeys[e.Row.RowIndex]["carnum"].ToString()
                && !string.IsNullOrEmpty(this.GridView1.DataKeys[e.Row.RowIndex]["carnum_"].ToString()))
            {
                ((DataControlFieldCell)e.Row.Cells[9]).ForeColor = System.Drawing.Color.Red;
            }
            //表底数一栏显示上次表底数。
            ((DataControlFieldCell)e.Row.Cells[11]).ToolTip = "上次公里底数：" + (this.GridView1.DataKeys[e.Row.RowIndex]["lastbds"] == DBNull.Value ? "无" : this.GridView1.DataKeys[e.Row.RowIndex]["lastbds"].ToString());
        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[1].Text = id.ToString();
        }

    }
    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        string jinggao3 = "<SCRIPT language=javascript>alert('";
        jinggao3 += "删除操作成功！";
        jinggao3 += "');</SCRIPT>";
        ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao3);
        //添加或删除之后要重新绑定卡号，否则显示的金额将不会更新。
        this.ddlCardNum.DataSourceID = dsCardNum.ID;
        this.ddlCardNum.Items.Clear();
        this.ddlCardNum.Items.Add(new ListItem("==请选择==", ""));
        this.ddlCardNum.DataBind();
        this.ddlCardNum0.DataSourceID = dsCardNum.ID;
        this.ddlCardNum0.Items.Clear();
        this.ddlCardNum0.Items.Add(new ListItem("==请选择==", ""));
        this.ddlCardNum0.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(this.txtChangeTime.Text.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请输入日期！');</SCRIPT>");
            this.txtChangeTime.Focus();
            return;
        }
        if (string.IsNullOrEmpty(this.ddlCardNum.SelectedValue.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请选择消费的油卡卡号！');</SCRIPT>");
            this.ddlCardNum.Focus();
            return;
        }
        if (string.IsNullOrEmpty(this.txtAmount.Text.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请输入消费金额（元）！');</SCRIPT>");
            this.txtAmount.Focus();
            return;
        }
        decimal amount = 0;
        if (!decimal.TryParse(this.txtAmount.Text.Trim(), out amount) || amount < 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('消费金额（元）必须为大于等于0的数字！');</SCRIPT>");
            this.txtAmount.Focus();
            return;
        }
        if (string.IsNullOrEmpty(this.ddlbzname.SelectedValue.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请选择加油班组！');</SCRIPT>");
            this.ddlbzname.Focus();
            return;
        }
        if (string.IsNullOrEmpty(this.ddlCarNum.SelectedValue.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请选择加油车号！');</SCRIPT>");
            this.ddlCarNum.Focus();
            return;
        }
        //如果是汽车，则加油量、公里底数必填
        decimal oil = 0;
        decimal bds = 0;
        if (this.ddlCarNum.SelectedValue.Trim().EndsWith("|1"))
        {
            //加油量（升）
            if (string.IsNullOrEmpty(this.txtOil.Text.Trim()))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请输入加油量（升）！');</SCRIPT>");
                this.txtOil.Focus();
                return;
            }
            if (!decimal.TryParse(this.txtOil.Text.Trim(), out oil) || oil < 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('加油量（升）必须为大于等于0的数字！');</SCRIPT>");
                this.txtOil.Focus();
                return;
            }
            //公里底数（KM
            if (string.IsNullOrEmpty(this.txtBDS.Text.Trim()))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请输入公里底数（KM）！');</SCRIPT>");
                this.txtBDS.Focus();
                return;
            }
            if (!decimal.TryParse(this.txtBDS.Text.Trim(), out bds) || bds < 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('公里底数（KM）必须为大于等于0的数字！');</SCRIPT>");
                this.txtBDS.Focus();
                return;
            }
        }
        if (!this.fPic.HasFile && this.hidPic_base64.Text.Length == 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "aa1", "<SCRIPT language=javascript>alert('请选择上传或拍摄加油小票照片！');</SCRIPT>");
            this.fPic.Focus();
            return;
        }
        try
        {
            string ext = ".jpg";
            string picfilename = this.ddlCardNum.SelectedValue + "_" + this.txtChangeTime.Text + "_" + DateTime.Now.Ticks;
            if (this.fPic.HasFile)
            {
                string[] exts = new string[] { ".jpg", ".jpeg", ".gif", ".png" };
                ext = System.IO.Path.GetExtension(this.fPic.PostedFile.FileName).ToLower();
                if (!exts.Contains(ext))
                {
                    string err1 = "<SCRIPT language=javascript>alert('";
                    err1 += "加油小票只允许上传照片，格式为:.jpg、.jpeg、.gif、.png。";
                    err1 += "');</SCRIPT>";
                    ClientScript.RegisterStartupScript(this.GetType(), "err1", err1);
                    return;
                }
                this.fPic.PostedFile.SaveAs(Server.MapPath("~/upload/" + picfilename + ext));
            }
            else
            {
                byte[] arr = Convert.FromBase64String(this.hidPic_base64.Text.Substring(23));
                System.IO.File.WriteAllBytes(Server.MapPath("~/upload/" + picfilename + ext), arr);
            }
            //获取上次此车的表底数
            string sql = @"SELECT TOP(1) BDS FROM [youkaguanli_card_detail]
WHERE CARNUM='{0}' AND TYPE=1 AND INOUT=-1 AND CHANGETIME < getdate()
ORDER BY CHANGETIME DESC,ADDTIME DESC,ID DESC";
            decimal lastbds = 0;
            try
            {
                sqlcon = new SqlConnection(strCon);
                SqlDataAdapter myda = new SqlDataAdapter(string.Format(sql, this.ddlCarNum.SelectedItem.Text), sqlcon);
                System.Data.DataSet myds = new System.Data.DataSet();
                myda.Fill(myds, "table");
                if (myds.Tables[0].Rows.Count > 0 && myds.Tables[0].Rows[0]["bds"] != DBNull.Value)
                {
                    lastbds = (decimal)myds.Tables[0].Rows[0]["bds"];
                }
            }
            catch (SqlException) { throw; }

            //构造要插入的数据
            SqlDataSource1.InsertParameters["cardid"].DefaultValue = this.ddlCardNum.SelectedValue;
            SqlDataSource1.InsertParameters["changetime"].DefaultValue = this.txtChangeTime.Text;
            SqlDataSource1.InsertParameters["amount"].DefaultValue = "-" + this.txtAmount.Text;
            SqlDataSource1.InsertParameters["jgname"].DefaultValue = this.ddlbzname.SelectedValue.Substring(0, this.ddlbzname.SelectedValue.IndexOf("|"));
            SqlDataSource1.InsertParameters["bzname"].DefaultValue = this.ddlbzname.SelectedItem.Text;
            SqlDataSource1.InsertParameters["carnum"].DefaultValue = this.ddlCarNum.SelectedItem.Text;
            SqlDataSource1.InsertParameters["pic"].DefaultValue = picfilename + ext;
            SqlDataSource1.InsertParameters["memo"].DefaultValue = this.txtMemo.Text.Replace("\r\n", "<br/>");
            SqlDataSource1.InsertParameters["addname"].DefaultValue = this.Label3.Text;
            SqlDataSource1.InsertParameters["addip"].DefaultValue = Page.Request.UserHostAddress.ToString().Trim();
            //油耗、表底数、上次表底数、百公里油耗
            SqlDataSource1.InsertParameters["oil"].DefaultValue = oil == 0 ? string.Empty : oil.ToString();
            SqlDataSource1.InsertParameters["lastbds"].DefaultValue = lastbds == 0 ? string.Empty : lastbds.ToString();
            SqlDataSource1.InsertParameters["bds"].DefaultValue = bds == 0 ? string.Empty : bds.ToString();
            decimal bglyh = oil == 0 || lastbds == 0 || bds == 0 ? 0 : (oil / (bds - lastbds) * 100);//油耗=加油量÷(二次公里数-一次公里数)×100 
            SqlDataSource1.InsertParameters["bglyh"].DefaultValue = bglyh == 0 ? string.Empty : bglyh.ToString();
            int success = SqlDataSource1.Insert();

            string jinggao3 = "<SCRIPT language=javascript>alert('";
            jinggao3 += success > 0 ? "油卡消费记录添加成功！" : "油卡消费记录添加失败";
            jinggao3 += "');</SCRIPT>";
            ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao3);

            if (success > 0)
            {
                ResetForm();
                this.GridView1.Focus();
            }
            else
            {
                this.Button1.Focus();
            }
        }
        catch (SqlException)
        {
            throw;
        }
    }
    protected void ResetForm()
    {
        this.txtChangeTime.Text = DateTime.Today.ToString("yyyy-MM-dd");
        this.ddlCardNum.SelectedValue = string.Empty;
        this.txtAmount.Text = string.Empty;
        this.ddlbzname.SelectedValue = string.Empty;
        this.ddlCarNum.SelectedValue = string.Empty;
        this.txtMemo.Text = string.Empty;

        //添加或删除之后要重新绑定卡号，否则显示的金额将不会更新。
        this.ddlCardNum.DataSourceID = dsCardNum.ID;
        this.ddlCardNum.Items.Clear();
        this.ddlCardNum.Items.Add(new ListItem("==请选择==", ""));
        this.ddlCardNum.DataBind();
        this.ddlCardNum0.DataSourceID = dsCardNum.ID;
        this.ddlCardNum0.Items.Clear();
        this.ddlCardNum0.Items.Add(new ListItem("==请选择==", ""));
        this.ddlCardNum0.DataBind();
        //如果该班组下只有一张卡，则选中此卡。
        if (this.ddlCardNum.Items.Count == 2) this.ddlCardNum.SelectedIndex = 1;
        //默认加油班组选中该班组。
        var o = this.ddlbzname.Items.FindByText(Label2.Text);
        if (o != null)
        {
            this.ddlbzname.SelectedIndex = this.ddlbzname.Items.IndexOf(o);
            //列出该班组下的车号
            dsCarNum.SelectParameters["banzu1"].DefaultValue = this.ddlbzname.SelectedItem.Text;
            this.ddlCarNum.DataSourceID = dsCarNum.ID;
            this.ddlCarNum.Items.Clear();
            this.ddlCarNum.Items.Add(new ListItem("==请选择==", ""));
            this.ddlCarNum.DataBind();
            //如果只有一张卡，则选中该卡对应的车号。
            if (this.ddlCarNum.Items.Count == 2)
            {
                this.ddlCarNum.SelectedIndex = 1;
            }
            else
            {
                if (!string.IsNullOrEmpty(this.ddlCardNum.SelectedValue))
                {
                    try
                    {
                        string car = this.ddlCardNum.SelectedValue.Substring(this.ddlCardNum.SelectedItem.Text.IndexOf(")") + 1);
                        var o1 = this.ddlCarNum.Items.FindByText(car);
                        if (o1 != null) this.ddlCarNum.SelectedIndex = this.ddlCarNum.Items.IndexOf(o1);
                    }
                    catch
                    {
                        this.ddlCarNum.SelectedIndex = 0;
                    }
                }
            }
        }
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        g_bind();
    }
    protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
    {
        this.txtTime0.Text = string.Empty;
        this.txtTime1.Text = string.Empty;
        this.ddlCardNum0.SelectedValue = string.Empty;
        this.ddlBzName0.SelectedValue = string.Empty;
        this.txtCarNum0.Text = string.Empty;
        this.txtOwner0.Text = string.Empty;
        this.txtMemo0.Text = string.Empty;
        g_bind();
    }
    public void g_bind()
    {
        Label_tiaojian.Text = "当前选择条件:";
        string sqlstr = @"
select t.*,c.owner,c.bzname as bzname_,c.carnum as carnum_,t.cardid+'【'+ISNULL(c.carnum,'无车号')+'】' as cardnum FROM (SELECT ROW_NUMBER() over (order by changetime desc,addtime desc,id desc) as i
,* FROM  youkaguanli_card_detail) as t
left join youkaguanli_card as c on t.cardid=c.cardnum
WHERE inout=-1 ";
        if (!Session["pn"].ToString().Contains("设备科"))
        {
            sqlstr += string.Format(" and (c.jgname='{0}' or c.bzname='{1}')", Session["pnchejian"].ToString(), Session["pn"].ToString());
        }
        if (!string.IsNullOrEmpty(this.txtTime0.Text) || !string.IsNullOrEmpty(this.txtTime1.Text))
        {
            string start = this.txtTime0.Text;
            if (this.txtTime0.Text.CompareTo(this.txtTime1.Text) > 0 && !string.IsNullOrEmpty(this.txtTime1.Text))
            {
                this.txtTime0.Text = this.txtTime1.Text;
                this.txtTime1.Text = start;
            }
            if (!string.IsNullOrEmpty(this.txtTime0.Text))
                sqlstr += " and changetime>=cast('" + this.txtTime0.Text + "' as smalldatetime)";
            if (!string.IsNullOrEmpty(this.txtTime1.Text))
                sqlstr += " and changetime<=cast('" + this.txtTime1.Text + "' as smalldatetime)";
            Label_tiaojian.Text += "时间范围：从" + (string.IsNullOrEmpty(this.txtTime0.Text) ? "?" : this.txtTime0.Text) + "至" + (string.IsNullOrEmpty(this.txtTime1.Text) ? "?" : this.txtTime1.Text) + "；  ";
        }
        if (!string.IsNullOrEmpty(this.ddlCardNum0.SelectedValue.Trim()))
        {
            sqlstr += " and cardid= '" + this.ddlCardNum0.SelectedValue.Trim() + "' ";
            Label_tiaojian.Text += "油卡卡号：'" + this.ddlCardNum0.SelectedItem.Text.Trim() + "'；  ";
        }
        if (!string.IsNullOrEmpty(this.ddlBzName0.SelectedValue.Trim()))
        {
            sqlstr += " and (t.jgname= '" + this.ddlBzName0.SelectedItem.Text.Trim() + "' or t.bzname='" + this.ddlBzName0.SelectedItem.Text.Trim() + "') ";
            Label_tiaojian.Text += "加油班组：'" + this.ddlBzName0.SelectedItem.Text.Trim() + "及下级''；  ";
        }
        if (!string.IsNullOrEmpty(this.txtCarNum0.Text.Trim()))
        {
            sqlstr += " and t.carnum like '%" + this.txtCarNum0.Text.Trim() + "%' ";
            Label_tiaojian.Text += "加油车号：包含'" + this.txtCarNum0.Text.Trim() + "'；  ";
        }
        if (!string.IsNullOrEmpty(this.txtOwner0.Text.Trim()))
        {
            sqlstr += " and c.owner like '%" + this.txtOwner0.Text.Trim() + "%' ";
            Label_tiaojian.Text += "持卡人：包含'" + this.txtOwner0.Text.Trim() + "'；  ";
        }
        if (!string.IsNullOrEmpty(this.txtMemo0.Text.Trim()))
        {
            sqlstr += " and t.memo like '%" + this.txtMemo0.Text.Trim() + "%' ";
            Label_tiaojian.Text += "备注：包含'" + this.txtMemo0.Text.Trim() + "'；  ";
        }
        if (Label_tiaojian.Text == "当前选择条件:") Label_tiaojian.Text = "当前选择条件:无";
        sqlstr += "order by i";
        SqlDataSource1.SelectCommand = sqlstr;
        GridView1.DataSourceID = SqlDataSource1.ID;
        GridView1.DataBind();
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        g_bind();
        ImageButton1.Focus();
    }
    protected void ddlbzname_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.ddlCarNum.Items.Clear();
        this.ddlCarNum.Items.Add(new ListItem("==请选择==", ""));
    }
    protected override void OnPreRenderComplete(EventArgs e)
    {
        if (!IsPostBack) ResetForm();
        base.OnPreRenderComplete(e);
    }
}